package com.edgar.loglib;

import android.os.Environment;
import android.util.Log;

import com.edgar.baselibrary.utils.IOUtils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by edgar on 2015/12/25.
 * The default print.
 * TODO Need add write to sd file.
 */
class DefaultWriteLog implements ILog{
    private File mLogWriteDir;  //日志目录.

    public DefaultWriteLog(File logDir){
        this.mLogWriteDir = logDir;
    }

    @Override
    public void onPrintLog(LogMessage logMessage) throws IOException{
        //如果sd卡根目录不存在,就不写
        if(logMessage != null && Environment.getExternalStorageDirectory().exists()){
            Date date = logMessage.getLogPrintTime();
            String logTime = Constants.LOG_LINE_DATE_FORMAT.format(date);
            String log = String.format(Constants.LOG_FORMAT,logTime,logMessage.getProcessId(),logMessage.getProcessName(),
                    logMessage.getThreadId(),logMessage.getLogLevel(), logMessage.getTag(),
                    logMessage.getClassName(),logMessage.getMethodName(),logMessage.getLineNum(),logMessage.getMessage());
            try {
                deleteOverdueLogFile();
                writeFile(new File(mLogWriteDir,Utils.generateFileName(date)),log);
            } catch (IOException e) {
                Log.e("Log","Write file error.");
                throw e;
            }
        }
    }

    /**
     * 删除过期文件,暂存7天
     */
    private void deleteOverdueLogFile(){
        File[] files = mLogWriteDir.listFiles();
        if(files != null && files.length > 0){
            Calendar calendar = Calendar.getInstance();
            for (File logFile : files){
                if(logFile.exists()){
                    //取得日志文件名中的日期
                    String dateStr = logFile.getName().replace(Constants.LOG_FILE_PREFIX, "");
                    dateStr = dateStr.replace(Constants.LOG_FILE_SUFFIX,"");
                    calendar.setTimeInMillis(System.currentTimeMillis());
                    calendar.set(Calendar.DATE,calendar.get(Calendar.DATE)-7);
                    if(isDateBefore(dateStr,calendar.getTime())){
                        if(logFile.delete()){
                            Log.i("Log","Delete log file success.");
                        }
                    }
                }
            }
        }
    }

    private boolean isDateBefore(String firstDate,Date secondDate){
        try {
            Date date = Constants.LOG_FILE_FORMAT.parse(firstDate);
            return date.before(secondDate);
        } catch (ParseException e){
            return false;
        }
    }

    /**
     * 写入日志文件
     * @param logFile 日志文件
     * @param log 日志信息
     */
    private void writeFile(File logFile,String log)throws IOException{
        if(!logFile.exists()){
            //文件创建失败
            if(!logFile.createNewFile()){
                return;
            }
        }
        FileWriter fileWriter = new FileWriter(logFile,true);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        try {
            bufferedWriter.write(log);
            bufferedWriter.newLine();
            bufferedWriter.flush();
        } finally {
            IOUtils.closeQuietly(fileWriter);
            IOUtils.closeQuietly(bufferedWriter);
        }
    }
}